﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace Marmat.Common.Http
{
    internal class HttpResultCommandFactoryInterceptor : HttpCommandFactoryInterceptor
    {
        public override object DeserializeResultValue(object value, Type type)
        {
            if (value is string str && string.IsNullOrEmpty(str))
                return null;

            Result result;
            if (value is Newtonsoft.Json.Linq.JToken body)
                result = body.ToObject<Result>();
            else
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result>(value.ToString());

            if (result.Status != 200)
                throw new ServiceException(result.Status, result.Message);

            if (type == typeof(void))
            { }
            else if (result.Data != null && type != typeof(object))
            {
                if (result.Data is Newtonsoft.Json.Linq.JToken token)
                    result.Data = token.ToObject(type);
                else if (type.IsClass && type != typeof(string))
                    result.Data = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Data.ToString(), type);
            }
            return result.Data;
        }
    }
}